package com.maktoub.apigateway;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.maktoub.apigateway.exception.BaseException;
import com.maktoub.common.model.baseresponse.CheckOkMes;
import com.maktoub.common.model.entity.InterfaceInfo;
import com.maktoub.common.model.entity.UserInterfaceInfo;
import com.maktoub.common.service.RemoteInterfaceInfoService;
import com.maktoub.common.service.RemoteUserInterfaceInfoService;
import com.maktoub.common.service.RemoteUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.reactivestreams.Publisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.*;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class CustomGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${spring.cloud.gateway.routes[0].uri}")
    private String  INTERFACE_DOMAIN;

    @DubboReference
    private RemoteUserService remoteUserService;
    @DubboReference
    private RemoteUserInterfaceInfoService remoteUserInterfaceInfoService;


    @DubboReference
    private RemoteInterfaceInfoService remoteInterfaceInfoService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //+ 请求日志记录，全局过滤器
        ServerHttpRequest request = exchange.getRequest();
        saveReqLog(request);

        //+ 请求染色, 在全局过滤器中实现了

        // 黑白名单
        String hostString = request.getRemoteAddress().getHostString();
        boolean is_black = check_Black(hostString);
        // TODO: 2024/5/19 前端开发接口的人员黑名单添加
        if (is_black ) {
            exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
            String message = "您已被列入黑名单！";
            return logAndReturnERR(exchange,HttpStatus.NOT_FOUND,message);
//            return exchange.getResponse().setComplete();
        }

        String path = request.getPath().value();
        String method = request.getMethod().toString();

        //+ todook 接口存在,方法匹配,后期开发后端系统提供接口，interfaceMapper，
        InterfaceInfo interfaceInfo;
        try {
            // sdk传过来地址，method，判断是否存在
            interfaceInfo= remoteInterfaceInfoService
                    .checkInterfaceExist(INTERFACE_DOMAIN + path, method);
        }
        catch (Exception e){
            String message = "系统异常！";
            return logAndReturnERR(exchange,HttpStatus.INTERNAL_SERVER_ERROR,message);
        }
        if(interfaceInfo==null){
            String message = "此接口不存在！";
            return logAndReturnERR(exchange,HttpStatus.NOT_FOUND,message);
        }

        //+ 签名认证，鉴权，
        HttpHeaders headers = request.getHeaders();
        String accessKey = headers.getFirst ("accessKey");
        String timestamp = headers.getFirst("timestamp");
        String random = headers.getFirst("random");
        String body = headers.getFirst("body");
//        try {
//            body = URLDecoder.decode(body, "utf-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//            String message = "解决中文乱码失败！";
//            return logAndReturnERR(exchange,HttpStatus.NOT_FOUND,message);
//        }
        String sign = headers.getFirst("sign");
        //签名校验
        CheckOkMes checkOkMes = remoteUserService.checkMes( accessKey,timestamp,random,body,sign);

        if(checkOkMes.getStatus()!=200){
            return logAndReturnERR(exchange,HttpStatus.valueOf(checkOkMes.getStatus()),checkOkMes.getMesage());
        }
        Long inerfaceId = interfaceInfo.getId();

        // 调用之前判断是否还剩余调用次数，ak判断
        UserInterfaceInfo userInterfaceInfo = remoteUserInterfaceInfoService.checkLeftNum(accessKey,inerfaceId);
        if (userInterfaceInfo ==null){
            String message = "暂无获得调用权限！";
            return logAndReturnERR(exchange,HttpStatus.UNAUTHORIZED,message);
        }
        Long leftNum = userInterfaceInfo.getLeftNum();
        Long totalNum = userInterfaceInfo.getTotalNum();

        // todo 添加接口的时候，赋值给管理员用户-1
        if(totalNum==-1){//代表无穷

        }
        else {  //不用判断次数
            if (leftNum >= totalNum) {
                String message = "调用次数用尽！再去开通吧~！";
                return logAndReturnERR(exchange, HttpStatus.UNAUTHORIZED, message);
            }
        }

        //+ 请求转发，配置文件的router中已经实现,这里经过了各层过滤之后转到对应服务

        //+ 响应日志,装饰器模式，装饰信息，响应码判断
        Mono<Void> filter = saveResLogAndAddCount(exchange, chain,accessKey,inerfaceId);
//        saveResLog(exchange.getResponse());//这个没有处理异步

        return filter;
    }

    @Override
    public int getOrder() {
        return -1;
    }

    /**
     * 处理响应数据，装饰器
     * @param exchange
     * @param chain
     * @return
     */
    public Mono<Void> saveResLogAndAddCount(ServerWebExchange exchange, GatewayFilterChain chain,
                                            String accessKey,Long interfaceId) {
        try {
            ServerHttpResponse originalResponse = exchange.getResponse();
            DataBufferFactory bufferFactory = originalResponse.bufferFactory();
            HttpStatus statusCode = originalResponse.getStatusCode();
            if (statusCode != HttpStatus.OK) {
                return chain.filter(exchange);//降级处理返回数据
            }
            //增强，装饰
            ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
               //调用完才会执行
                @Override
                public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                    if (body instanceof Flux) {
                        Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                        return super.writeWith(fluxBody.buffer().map(dataBuffers -> {
                            // 合并多个流集合，解决返回体分段传输
                            DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
                            DataBuffer buff = dataBufferFactory.join(dataBuffers);
                            byte[] content = new byte[buff.readableByteCount()];
                            buff.read(content);
                            DataBufferUtils.release(buff);//释放掉内存

                            //排除Excel导出，不是application/json不打印。若请求是上传图片则在最上面判断。
                            MediaType contentType = originalResponse.getHeaders().getContentType();
                            if (!MediaType.APPLICATION_JSON.isCompatibleWith(contentType)) {
                                return bufferFactory.wrap(content);
                            }

                            //调用次数加一,用accessKey相当于用id
                            boolean b = remoteUserInterfaceInfoService.addInvokeCount(accessKey, interfaceId);
                            if(!b){
                                log.info("更新调用次数失败");
                                String message = "系统异常！";
                                //调用失败则服务器异常
                                exchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
                                DataBuffer wrap = bufferFactory.wrap(message.getBytes());
                                return wrap;
                            }
                            // 构建返回日志
                            String joinData = new String(content);//真实响应结果
                            String result = modifyBody(joinData);
                            List<Object> rspArgs = new ArrayList<>();
                            rspArgs.add(originalResponse.getStatusCode().value());
                            rspArgs.add(result);
                            log.info("响应结果： {} 响应值：{}", rspArgs.toArray());//记录日志信息
                            getDelegate().getHeaders().setContentLength(result.getBytes().length);
                            return bufferFactory.wrap(result.getBytes());
                        }));
                    } else {
                        log.error("响应异常：  {} ", getStatusCode());
                    }
                    return super.writeWith(body); //正常的接口
                }
            };
            //设置为装饰过的
            return chain.filter(exchange.mutate().response(decoratedResponse).build());

        } catch (Exception e) {
            log.error("错误信息：{}",e.getMessage());
            return chain.filter(exchange);
        }
    }

    //返回统一的JSON日期数据 2024-02-23 11:00， null转空字符串
    private String modifyBody(String jsonStr){
        JSONObject json = JSON.parseObject(jsonStr, Feature.AllowISO8601DateFormat);
        JSONObject.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm";
        return JSONObject.toJSONString(json, (ValueFilter) (object, name, value) -> value == null ? "" : value, SerializerFeature.WriteDateUseDateFormat);
    }

    private Mono<Void>  logAndReturnERR(ServerWebExchange exchange,HttpStatus httpStatus,String message){
        exchange.getResponse().setStatusCode(httpStatus);
        log.error("返回状态码：{}",httpStatus);
        log.error("错误信息：{}",message);
        DataBuffer dataBuffer = exchange.getResponse().bufferFactory().wrap(message.getBytes());
        return  exchange.getResponse().writeWith(Flux.just(dataBuffer));
    }


    private void saveReqLog(ServerHttpRequest request) {
        URI uri = request.getURI();
        log.info("请求地址：  {}", uri);
        HttpMethod method = request.getMethod();
        log.info("请求方法：  {}", method);
        HttpHeaders headers = request.getHeaders();
        log.info("请求头信息：  {}", headers);
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        log.info("Cookie信息：  {}", cookies);
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        log.info("请求参数：  {}", queryParams);
        Flux<DataBuffer> body = request.getBody();
        log.info("请求body：  {}", body);
        String hostString = request.getLocalAddress().getHostString();
        log.info("请求来源：  {}", hostString);
        String hostString1 = request.getRemoteAddress().getHostString();
        log.info("远程地址：  {}", hostString);
    }

    private boolean check_Black(String hostString) {


        Long expire = redisTemplate.getExpire(hostString);
        if (expire < 0) { //不在黑名单，或者之前在已过期
            return false;
        }
        return true;
    }




    private void saveResLog(ServerHttpResponse response) {
        HttpStatus statusCode = response.getStatusCode();
        log.info("响应码 {}",statusCode);
        HttpHeaders headers = response.getHeaders();
        log.info("响应头 {}", headers);
        MultiValueMap<String, ResponseCookie> cookies = response.getCookies();
        log.info("Cookie {}",cookies);
    }


}